//
//  MainViewController.swift
//  swiftweibo
//
//  Created by 吕建发 on 16/5/10.
//  Copyright © 2016年 cn.itcast. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        
        setTabBar()
    }

    
    // MARK: - 重写viewWillApear 设置按钮的frame
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 将按钮置于视图最上面
        tabBar.bringSubviewToFront(plusButton)
        
        let width = tabBar.bounds.width / CGFloat(childViewControllers.count) - 1
        
        plusButton.frame = CGRectInset(tabBar.bounds, width * 2, 0)
        
        
    }
    
    
    
    
    // MARK: - 懒加载加号按钮
    lazy var plusButton: UIButton = {
        
        let button = UIButton()
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        button.sizeToFit()
        
        return button
        
    }()
  
}

// MARK: - 添加自控制器的方法
extension MainViewController {
    
    private func addChildViewController(childController: UIViewController,imageName: String,title: String) {
        
        childController.title = title
        childController.tabBarItem.image = UIImage(named: imageName)
        childController.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.imageWithRenderingMode(.AlwaysOriginal)
        
        childController.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orangeColor() ], forState: .Selected)
        
        let nav = UINavigationController(rootViewController:childController)
        
        addChildViewController(nav)
        
    }
    
    private func addChildViewControllers() {
        addChildViewController(HomeViewController(), imageName: "tabbar_home", title: "首页")
        addChildViewController(MessageViewController(), imageName: "tabbar_message_center", title: "消息")
        
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverViewController(), imageName: "tabbar_discover", title: "发现")
        addChildViewController(ProfileViewController(), imageName: "tabbar_profile", title: "我")
    }
    
    
    
}
    

// MARK: - 设置tabbar
extension MainViewController{
    
    private func setTabBar() {
        
//        tabBar.shadowImage = UIImage.lv_singleDotImage(UIColor(white: 0.9, alpha: 1.0))
        
        tabBar.shadowImage = UIImage()
        tabBar.backgroundImage = UIImage(named: "tabbar_background")
        
        tabBar.addSubview(plusButton)
    }
    
}

















